<template>
  <div>  
    <div class="view-toggle">
      <el-button-group>
        <el-button :type="viewMode === 'table' ? 'primary' : ''"  @click="viewMode = 'table'"title="表格视图">
          <el-icon><Grid /></el-icon>
        </el-button>
         <el-button :type="viewMode === 'card' ? 'primary' : ''"@click="viewMode = 'card'"title="卡片视图">
          <el-icon><Menu /></el-icon>
        </el-button>
      </el-button-group>
    </div>
    <!-- 表格视图 -->
    <el-table v-if="viewMode === 'table'" :data="GoodsArr" v-loading="loading" style="width: 100%" empty-text="暂无上架商品">
      <el-table-column prop="shopname" label="商品名称" width="120" />
      <el-table-column prop="recommend" label="商品介绍" width="120" />
      <el-table-column prop="price" label="价格" width="120">
        <template #default="{ row }">
          {{ row.price/100 }} 元
        </template>
      </el-table-column>
      <el-table-column label="卖家ID" width="240" >
        <template #default="{ row }">
          <p class="seller" @click="catUserShopUid(row.uid)">卖家ID: {{ row.uid }}</p>
        </template>
      </el-table-column>
      <el-table-column label="卖家昵称" width="240" >
        <template #default="{ row }">
          <router-link to="/userShop" class="uid-link">
            <p class="seller" @click="catUserShopName(row.uname)">卖家昵称: {{ row.uname }}</p>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="下架时间">
        <template #default="{ row }">
          {{ formatTime(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button @click="handleBuy(row.id,row.uid,row.price)">立刻购买喵</el-button>
        </template>
      </el-table-column>
    </el-table> 
    <!-- 卡片视图 -->
    <div v-else v-loading="loading" class="card-list goods-container">
      <el-empty v-if="!GoodsArr.length && !loading" description="暂无上架商品" />
      <el-row :gutter="20">
        <el-col v-for="(item, index) in GoodsArr" :key="index":xs="24" :sm="12" :md="8" :lg="4" class="card-col" >
          <el-card class="goods-card">
            <!-- 商品信息 -->
            <div class="goods-info">
              <div class="title-price">
                <h3 class="name">{{ item.shopname }}</h3>
                <span class="price">{{ item.price/100 }} 元</span>
              </div>
              <div class="meta-info">
                <p class="recommend">{{ item.recommend }}</p>
                <p class="seller" @click="catUserShopUid(item.uid)">卖家ID: {{ item.uid }}</p>
                <router-link to="/userShop" class="uid-link">
                  
                  <p class="seller" @click="catUserShopName(item.uname)">卖家昵称: {{ item.uname }}</p>
                </router-link>
                <p class="end-time">下架时间: {{ formatTime(item.endTime) }}</p>
              </div>
              <el-button class="buy-btn" @click="handleBuy(item.id,item.uid,item.price)">立即购买喵</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>  
</template>
  
<script setup>
  import { useRouter } from 'vue-router';
  import { ref, onMounted,reactive} from 'vue'
  import { ElTable, ElTableColumn} from 'element-plus'
  import { Grid, Menu } from '@element-plus/icons-vue'
  import { useStore } from 'vuex'
  import { ElMessage } from 'element-plus';
  import * as contract from '../../test/Truffle-ABI.js'
  import axios from 'axios';
  const loading = ref(false)
  const GoodsArr = ref([])
  const viewMode = ref('card')
  const store = useStore();
  const router = useRouter()

  function catUserShopUid(uid) {
    store.commit('updateUserInitUid',uid)
    const txt = 'Uid'+uid+'的上架商品'
    store.commit('setTxt',txt)
  }
    
  function catUserShopName(name) {
    const txt = '昵称为'+name+'的上架商品'
    store.commit('setTxt',txt)
  }
  
  const handleBuy = async (id,uid,price) => {
    try{
      const username = store.state.user.name
      const touid = store.state.user.uid
      const values = store.state.user.values
      if (uid==touid){
        ElMessage.error({message: `相同用户不能交易喵！`,})
        return
      }
      if(touid==0){
        ElMessage.error({message: `先登录才可以交易喵！`,})
        return
      }
      if(values<=price){
        ElMessage.error({message: `余额不够喵`,})
        return
      }
      await contract.shopping(uid,touid,id)
      const info = await contract.getUser(username);
      const user =reactive({
        values: info.values
      });
      //存储用户信息到Vuex
      store.commit('updatevalues',user.values);
      ElMessage.success({message: `交易成功喵！`,})
      router.go(0)
    }
    catch (error) {
      console.error('购买商品失败:', error)
      ElMessage.error('购买商品失败，请稍后重试')
    }
    
  }
    // 格式化时间方法
  const formatTime = (timestamp) => {
      if (!timestamp) return '未知时间'
      const date = new Date(timestamp/1000)
      return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`
  }
  
  
  // 获取商品数据
  const fetchGoods = async () => {
    try {
      loading.value = true
      GoodsArr.value = [] // 清空旧数据
      await contract.initWeb3();
      const data = await contract.getAllActiveGoods()
        for (let i = 0; i < data.length; i++) {
          try {
            const response = await axios.get(`http://localhost:3001/api/data/${data[i].id}`)
            const name = await contract.getUserByUid(data[i].seller)
            const Goods = {
              id: data[i].id,
              uid: data[i].seller,
              uname: name,
              img: response.data.img,
              shopname: response.data.name,
              recommend: response.data.recommend,
              price: data[i].price,
              endTime: data[i].endTime
            }
            console.log('获取:', Goods)
            GoodsArr.value.push(Goods)
          } catch (innerError) {
            console.error(`商品${data[i].id}详情获取失败:`, innerError)
          }
        }
    } catch (error) {
      console.error(error)
      ElMessage.error('商品加载失败，请稍后重试')
    } finally {
      loading.value = false
    }
  }
  
  onMounted(() => {
    store.commit('setTxt','首页')
    fetchGoods()
  })
</script>
  
  <style scoped>
    .uid-link {
      text-decoration: none;
    }
    
    .goods-containerTable {
        position: relative;
        
    }
    
   
    .card-list {
        padding: 20px;
    }
  
    .card-col {
        margin-bottom: 20px;
    }
  
    .goods-card {
        height: 100%;
        transition: transform 0.3s;
    }
  
    .goods-card:hover {
        transform: translateY(-5px);
    }
  
    .image-wrapper {
        position: relative;
        padding-top: 100%;
        background: #f5f7fa;
    }
  
    .goods-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }
  
    .goods-info {
        padding: 15px;
    }
  
    .title-price {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
    }
  
    .name {
        margin: 0;
        font-size: 16px;
        color: #303133;
    }
  
    .price {
        font-size: 18px;
        color: #f56c6c;
        font-weight: bold;
    }
  
    .meta-info {
        margin: 12px 0;
        font-size: 12px;
        color: #909399;
    }
  
    .meta-info p {
        margin: 6px 0;
    }
  
    .buy-btn {
        width: 100%;
        margin-top: 10px;
    }
  
    .view-toggle {
        margin-bottom: 20px;
        display: flex;
        justify-content: flex-end;
    }
  
    .el-button-group {
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
  
    .el-button {
        padding: 10px 15px;
        transition: all 0.3s;
    }
    
    .el-button:not(.is-primary) {
        background: #fff;
        border-color: #dcdfe6;
    }
  
    .el-button + .el-button {
        margin-left: -1px;
    }
  
    .el-icon {
        font-size: 18px;
    }
  
    .image-error {
        background: #f5f7fa;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        color: #909399;
    }
</style>